import {
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';
import { User } from 'src/interfaces/user.interface';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  public roles: string[];
  constructor(private reflector: Reflector) {
    super(reflector);
  }
  canActivate(context: ExecutionContext) {
    this.roles = this.reflector.get<string[]>('roles', context.getHandler());
    return super.canActivate(context);
  }
  handleRequest(err: any, user: any) {
    // 可以抛出一个基于info或者err参数的异常
    if (err || !user) {
      throw err || new UnauthorizedException();
    }
    if (!this.matchRoles(user)) {
      throw new UnauthorizedException({
        code: 401,
        error: 'Insufficient permissions',
        msg: '您所在的用户组权限不足。',
      });
    }
    return user;
  }
  matchRoles(user: User): boolean {
    if (this.roles) {
      console.log(this.roles, user);
      for (const role of this.roles) {
        const index = user.roles.indexOf(role);
        if (index >= 0) {
          return true;
        }
      }
      return false;
    } else {
      return true;
    }
  }
}
